<template>
  <div>
    <div class="row-main">
      <el-button type="shenda" size="small" @click="showDialog" icon="el-icon-receiving" v-has="'notCardStop'">批量拆机</el-button>
      <el-button type="shenda" size="small" @click="exlDownload" icon="el-icon-download" :loading="loading">导出</el-button>
      <el-table v-has="'cardListOemListTable'" :header-cell-style="{'background':'#F2F6FC','color':'#606266' }"
                :data="tableData"
                ref="table" tooltip-effect="dark" class="row-main-table" @selection-change="handleSelectionChange"
                v-loading.fullscreen="tableLoading" element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)"
                :row-key="getRowKeys">
        <el-table-column type="selection" :reserve-selection="true" align="center"></el-table-column>
        <el-table-column prop="id" label="业务号码" align="center"></el-table-column>
        <el-table-column prop="iccid" label="ICCID" align="center"></el-table-column>
        <el-table-column prop="dictChannelCardStatusName" label="卡状态" align="center"></el-table-column>
        <el-table-column prop="insertTime" label="创建时间" align="center"></el-table-column>
        <el-table-column prop="cardCount" label="操作" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <div>
                <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-button class="operation" @click="showSendGoodsBtn(scope.row)" v-preventReClick :disabled="scope.row.dictChangeStatus === 'WAIT_CONFIRM'|| scope.row.dictChangeStatus === 'WAIT_CHANGE'|| scope.row.dictChangeStatus === 'WAIT_TRANSFORM'|| scope.row.dictChangeStatus === 'CHANGE_SUCCESS'|| scope.row.dictChangeStatus === 'BE_REMOVED'">发货</el-button>
                <el-button class="operation" @click="showterminatedBtn(scope.row)" v-preventReClick :disabled="scope.row.dictChangeStatus === 'WAIT_CONFIRM'|| scope.row.dictChangeStatus === 'WAIT_CHANGE'|| scope.row.dictChangeStatus === 'WAIT_TRANSFORM'|| scope.row.dictChangeStatus === 'WAIT_SEND'|| scope.row.dictChangeStatus === 'BE_REMOVED'">拆机</el-button>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="currentPage" :page-size="pageSize" class="row-main-pager"
                     layout="total, sizes, prev, pager, next, jumper" :total="totalPage"
                     :page-sizes="[10,20,50,100]" background></el-pagination>
      </div>
    </div>
    <el-dialog class="delete" top="30vh" :visible.sync="showSendGoods" :append-to-body="true" width="30%">
      <el-form class="demo-ruleForm" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="客户收货地址">
          <el-input type="textarea" :rows="1" :readonly="true" v-model="ruleForm.shippingAddress"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item label="客户电话">
          <el-input v-model="ruleForm.customerMobile" size="small" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="运单号" prop="courierNumber" ref="input">
          <el-input v-model="ruleForm.courierNumber" size="small" v-focus></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
      <el-button @click="showSendGoods = false" size="small">取 消</el-button>
      <el-button type="primary" @click="changeCardDialogbl('ruleForm')" size="small"
                 v-preventReClick>确 定</el-button></span>
    </el-dialog>
    <el-dialog class="delete" top="33vh" :visible.sync="changeCardDialog" :append-to-body="true" width="30%"><span
      style="display: flex; justify-content: center;">确定发货吗？</span><span class="dialog-footer" slot="footer">
      <el-button @click="changeCardDialog = false" size="small">取 消</el-button>
      <el-button type="primary" @click="sendCard()" size="small" v-preventReClick>确 定</el-button></span></el-dialog>
    <el-dialog class="delete" top="30vh" :visible.sync="showNumDetail" :append-to-body="true" width="30%">
      <el-form class="demo-ruleForm" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="客户收货地址">
          <el-input type="textarea" :rows="1" :readonly="true" v-model="ruleForm.shippingAddress"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item label="客户电话">
          <el-input v-model="ruleForm.customerMobile" size="small" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="运单号" prop="courierNumber1" ref="input">
          <el-input v-model="courierNumber1" size="small" :readonly="true"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
      <el-button @click="showNumDetail = false" size="small">关 闭</el-button></span>
    </el-dialog>
    <!-- 批量拆机确认-->
    <el-dialog class="delete" top="33vh" :visible.sync="showStopCard" :append-to-body="true" width="30%"><span
      style="display: flex; justify-content: center;">拆机操作前请确认是否在线下通过运营商完成拆机，如未完成，请与运营商联系拆机！</span>
      <el-form class="demo-ruleForm" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px"
               style="margin-top:10px;">
        <el-form-item label="拆机原因" prop="reason">
          <el-input type="textarea" :rows="1" v-model="ruleForm.reason" size="small" v-focus></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
      <el-button @click="showStopCard = false" size="small">取 消</el-button>
      <el-button type="primary" @click="stopCardBtn('ruleForm')" size="small" v-preventReClick>确 定</el-button></span>
    </el-dialog>
    <el-dialog class="delete" top="33vh" :visible.sync="terminatedDialog" :append-to-body="true" width="30%"><span
      style="display: flex; justify-content: center;">确定拆机吗？</span><span class="dialog-footer" slot="footer">
      <el-button @click="terminatedDialog = false" size="small">取 消</el-button>
      <el-button type="primary" @click="stopCardBtnsubmit()" size="small" v-preventReClick>确 定</el-button></span>
    </el-dialog>
    <el-dialog class="delete" top="33vh" :visible.sync="showStopCard1" :append-to-body="true" width="30%"><span
      style="display: flex; justify-content: center;">拆机操作前请确认是否在线下通过运营商完成拆机，如未完成，请与运营商联系拆机！</span>
      <el-form class="demo-ruleForm" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px"
               style="margin-top:10px;">
        <el-form-item label="拆机原因" prop="reason">
          <el-input type="textarea" :rows="1" v-model="ruleForm.reason" size="small" v-focus></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
      <el-button @click="showStopCard1 = false" size="small">取 消</el-button>
      <el-button type="primary" @click="stopCardBtn1('ruleForm')" size="small" v-preventReClick>确 定</el-button></span>
    </el-dialog>
    <el-dialog class="delete" top="33vh" :visible.sync="terminatedDialog1" :append-to-body="true" width="30%"><span
      style="display: flex; justify-content: center;">确定拆机吗？</span><span class="dialog-footer" slot="footer">
      <el-button @click="terminatedDialog1 = false" size="small">取 消</el-button>
      <el-button type="primary" @click="stopCardBtnsubmit1" size="small" v-preventReClick>确 定</el-button></span>
    </el-dialog>
  </div>
</template>

<script>
import {
  sendCard,
  coldCardList,
  removeCard
} from '@/api/getData'

export default {
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector('input').focus()
      }
    }
  },
  name: 'List',
  data() {
    return {
      pagekey: '',
      maxPage: 1,
      totalPage: 0,
      ruleForm: {
        courierNumber: '',
        shippingAddress: '',
        customerMobile: '',
        reason: '',
      },
      form: {
        oldCardNumber: '',
        newCardNumber: '',
        dictChangeType: '',
        dictChangeStatus: '',
        insertTime: '',
        updateTime: '',
      },
      courierNumber1: '',
      id: '',
      terminatedDialog: false,
      terminatedDialog1: false,
      textarea: '',
      tableData: [],
      tableData1: [],
      pageSize: 10,
      currentPage: 1,
      ascs: [],
      descs: [],
      dictChannelCardTypeSearch: '',
      showSendGoods: false,
      changeCardDialog: false,
      showNumDetail: false,
      showBatchStopCard: "确认批量设置停机吗？",
      tableChecked: [],
      showStopCard: false,
      showStopCard1: false,
      loading: false,
      tableLoading: false,
      ids: [],
      rules: {
        courierNumber: [
          {required: true, message: '请填写运单号', trigger: 'blur'},
          {min: 1, max: 20, message: '长度不能超过20位', trigger: 'blur'}
        ],
        reason: [
          {required: true, message: '请填写拆机原因', trigger: 'blur'},
          {min: 1, max: 20, message: '长度不能超过20位', trigger: 'blur'}
        ],
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  },
  computed: {},
  created() {
    this.coldCard()
  },
  mounted() {

  },
  methods: {
    getRowKeys(row) {
      return row.id
    },
    handleSelectionChange(val) {
      this.tableChecked = val
      const length = this.tableChecked.length
      //console.log(`共 ${length} 条`)
    },
    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.coldCard()
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`)
      this.currentPage = val
      this.coldCard()
    },
    async showDialog() {
      this.pagekey = await this.$getPageKey();
      if (this.tableChecked.length !== 0) {
        if (this.tableChecked.every(item => {
          return item.dictChangeStatus !== 'CHANGE_SUCCESS'
        })) {
          this.$message({message: '只有换卡成功的卡可以设置批量拆机', type: 'error'})
        } else {
          this.showStopCard = true
        }
      } else {
        this.$message({message: '请选择要操作的卡组', type: 'error'})
      }
    },
    //批量拆机
    async stopCardBtnsubmit() {
      let arrays = this.tableChecked.filter(item => item.dictChangeStatus === 'CHANGE_SUCCESS').map(item => {
        const obj = {}
        obj.id = item.id
        obj.oldCardId = item.oldCardId
        obj.reason = this.ruleForm.reason
        return obj
      })
      const returnData = await removeCard(
        arrays
      )
      if (returnData._result) {
        this.$message({message: '批量拆机成功', type: 'success'})
        this.showStopCard = false
        this.terminatedDialog = false
        this.coldCard()
      }
    },
    async stopCardBtnsubmit1() {
      const returnData = await removeCard(
        [{
          id: this.id,
          oldCardId: this.oldCardId,
          reason: this.ruleForm.reason
        }], {pagekey: this.pagekey}
      )
      if (returnData._result) {
        this.$message({message: '拆机成功', type: 'success'})
        this.showStopCard1 = false
        this.terminatedDialog1 = false
        this.coldCard()
      }
      this.pagekey = await this.$getPageKey();
    },
    //冷冻卡列表
    async coldCard() {
      let startTime = null
      let endTime = null
      if (this.form.insertTime !== '' && this.form.insertTime != null) {
        startTime = this.form.insertTime[0]
        endTime = this.form.insertTime[1]
      }
      let handleStartTime = null
      let handleEndTime = null
      if (this.form.updateTime !== '' && this.form.updateTime != null) {
        handleStartTime = this.form.updateTime[0]
        handleEndTime = this.form.updateTime[1]
      }
      this.tableLoading = true;
      const returnData = await coldCardList({
          page: {
            current: this.currentPage + '',
            size: this.pageSize + '',
            ascs: this.ascs,
            descs: this.descs
          }
        },
        {
          obj: this,
          key: 'tableLoading'
        })
      this.tableData = []
      if (returnData._result) {
        this.maxPage = Math.ceil(returnData.data.total / this.pageSize) // 分页的最大页数
        this.totalPage = returnData.data.total;
        // 数据回显
        returnData.data.records.map(item => {
          const obj = {}
          obj.id = item.id //id
          obj.iccid = item.iccid //iccid
          obj.dictChannelCardStatus = item.dictChannelCardStatus // 卡状态值
          obj.dictChannelCardStatusName = item.dictChannelCardStatusName // 卡状态
          obj.insertTime = item.insertTimeDate // 创建时间
          this.tableData.push(obj)
        })
        this.tableLoading = false
      }
    },
    //发货
    async sendCard() {

      const returnData = await sendCard({
        id: this.id,
        courierNumber: this.ruleForm.courierNumber
      }, {pagekey: this.pagekey})
      if (returnData._result) {
        this.changeCardDialog = false
        this.showSendGoods = false
        this.coldCard()
      }
      this.pagekey = await this.$getPageKey();
    },

    changeCardDialogbl(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.changeCardDialog = true
        } else {
          return false;
        }
      });
    },
    stopCardBtn(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.terminatedDialog = true
        } else {
          return false;
        }
      });
    },
    stopCardBtn1(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.terminatedDialog1 = true
        } else {
          return false;
        }
      });
    },
    async showSendGoodsBtn(card) {
      this.id = card.id
      this.ruleForm.shippingAddress = card.shippingAddress
      this.ruleForm.customerMobile = card.customerMobile
      this.ruleForm.reason = ""
      this.showSendGoods = true;
      this.pagekey = await this.$getPageKey();
    },
    async showterminatedBtn(card) {
      this.id = card.id
      this.oldCardId = card.oldCardId
      this.ruleForm.courierNumber = ""
      this.showStopCard1 = true
      this.pagekey = await this.$getPageKey();
    },
    showNumDetailBtn(card) {
      this.ruleForm.shippingAddress = card.shippingAddress
      this.ruleForm.customerMobile = card.customerMobile
      this.courierNumber1 = card.courierNumber
      this.showNumDetail = true
    },
    exlDownload() {
      this.loading = true;
      this.tableLoading = true;
      let obj = {
        iccid: this.form.iccid,
        cardNumber: this.form.cardNumber,
        dictBeforeStatus: this.form.dictBeforeStatus,
        page: {
          current: this.currentPage + '',
          size: this.totalPage + '',
          ascs: this.ascs,
          descs: this.descs
        }
      };
      let arr = new Array(...this.$refs.table.columns);
      arr.shift();
      let list = [];
      let filterVal = [];
      for (let item of arr) {
        list.push(item.label);
        filterVal.push(item.property);
      }
      list.pop();
      filterVal.pop();
      let info = {
        api: 'coldCardList',
        name: '冷冻卡列表'
      };
      this.tableLoading = false;
      this.loading = false;
      const {href} = this.$router.resolve({
        path: '/exl/exlDownload',
        query: {
          list: JSON.stringify(list),
          filterVal: JSON.stringify(filterVal),
          obj: JSON.stringify(obj),
          info: JSON.stringify(info),
        }
      });
      window.open(href, '_blank');
    }
  },

}
</script>

<style scoped lang="scss">
.el-popper[x-placement^=bottom] {
  margin-right: -31px;
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}

.el-popper[x-placement^=top] {
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;
  margin-right: -31px;

  button {
    display: block;
  }

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}
</style>
